'use strict';

const fs = require('fs');
const path = require('path');
const glob = require('glob');
// const command = require('commander');

function DocTools(config){
    /**
     * 获取文件后缀
     * @param {string} url
     */
    var getSuffix = function(url) {
        var arr = url.split('.');
        var len = arr.length;
        return arr[len - 1];
    }

    /**
     *
     * @param {string} filePath
     * @param {number} type
     */
    var readDirFileName = function(filePath, type) {
        console.log("当前目录：", filePath);
        var fileNameArray = [];
        fs.readdirSync(filePath, 'utf-8').forEach( (fileName)=> {
            var stat = fs.statSync(path.join(filePath, fileName));
            if (stat.isFile()) {
                if (getSuffix(fileName) == type) {
                    //console.log("文件：", path.join(filePath,fileName));
                    fileNameArray.push({ name: fileName, path: path.normalize(filePath)});
                }
            } else if (stat.isDirectory() && fileName !== ".git") {
                // console.log("文夹：", fileName);
                fileNameArray = fileNameArray.concat(readDirFileName(path.join(filePath, fileName), type));
            }
        });
        return fileNameArray;
    }

    /**
     * 修改文件名称
     * @param {*} sPath
     * @param {*} fileName
     * @param {*} newName
     */
    var reFimeName = function( sPath, oldName, newName) {
        if (!newName) {
            newName = newFileName(oldName);
        }
        oldName = path.join(sPath, oldName);
        newName = path.join(sPath, newName);

        if(oldName == newName){
            return;
        }

        fs.rename(oldName, newName, (err) => {
            if(err){
                console.log("修改文件名失败：",err, oldName, newName);
                return;
            }
            console.log("修改文件名成功：", oldName, newName);
        });
    }

    /**
     * 批量的重新命名文件名称 根据文件名称是否有 [xxx] 的符号
     */
    var changeAllFileName = function(rootPath){
        let files = readDirFileName(rootPath, 'md');
        files.forEach((ele)=>{
            //console.log("修改的文件：", JSON.stringify(ele));
            reFimeName(ele.path, ele.name);
        });
    }

    /**
     * 获取 获取新的文件名称
     * @param {string} oldName
     */
    var newFileName = function(oldName) {
        var strArray = oldName.split(".");
        var sub = oldName.match(/\[(\S*)\]/);
        if (sub) {
            return strArray.length > 1 ? sub[1] + "." + strArray[strArray.length - 1] : sub;
        }
        return oldName;
    }

    /**
     * 保存数据到 summary.json 文件中
     * @param {*} data
     */
    var saveFileName = function(data){
        let tmp = data.join('\n');
        if(typeof data == "object"){
            tmp = JSON.stringify(data);
        }else{
            tmp = data;
        }
        console.log("要写入的文件数据：", JSON.stringify(tmp));
        fs.writeFile(path.join(__dirname, "summary.json"), tmp, function (err) {
            if (err) throw err;
            console.log("summary.json 生成成功");
        });
    }

    /**
     * 获取指定路径下的所有文件 和目录列表
     * @param {*} filePaths
     */
    var getShortPath = function(root){
        let filePaths = glob.sync(root + "/**/*");
        let shortPaths = [];
        filePaths.forEach(filePath =>{
            let shortPath = path.normalize(filePath).replace(path.normalize(root), '').trim();
            let slug = shortPath.split('\\').join('/');

            let arr = slug.split("/");
            let filename = newFileName(arr[arr.length-1]);
            filename = filename.split('.')[0];
            shortPaths.push({ file: slug, alias: filename});
        });
        console.log(shortPaths);
        return shortPaths;
    }

    var readFileData = function(file){
      console.log("readFileData:",file);
        let data = fs.readFileSync(file, 'utf8');
        return data;
    }

    var _StringChange = function(a,b){
        let bufa = new Buffer(a);
        let bufb = new Buffer(b);
        for(let i =0; i < bufa.length; i++){
            bufb[i] = bufa[i]
        }
        return bufb.toString('utf8');
    }


    /**
     * ^[\/\*\n\bTitle][^]*[\n\bsort:\s+][0-9]\d*\n\*\/
     * @param {*} fileName
     * @param {*} datas
     */
    var _writHeadInfo = function(fileName, datas){
        //console.log("fileName:", fileName, " datas:", datas);
        var files = fs.readFileSync(fileName, 'utf8');
        let toChange = "/*\r\nTitle: " + datas.Title + "\r\nSort: " + datas.sort+"\r\n*/";
        let headDatas = files.substring(0, 200);
        if (/^[\/\*\r\n\bTitle:][^]*[\r\n\bSort:\s+][0-9]\d*\r\n\*\//g.test(headDatas)){
            //console.log("替换前数据：headDatas:", headDatas);
            let result = headDatas.replace(/^[\/\*\r\n\bTitle:][^]*[\r\n\bSort:\s+][0-9]\d*\r\n\*\//g, toChange);
            files = _StringChange(result, files);
        }else{
            files = toChange +"\r\n"+ files;
        }
        fs.writeFile(fileName, files, 'utf8', function (err) {
            if (err) {
                console.log("写入失败", toChange);
            }
        });
        return ;
    }

    /**
     * 根据 summary.json 写入排序头信息到文件中
     * @param {string} rootPath 指定排序的目录
     */
    var WritfileSort = function(rootPath, callback){
        //读取所有文件 md
        let fileNames = readDirFileName(path.normalize(rootPath), 'md');
        let sortData = JSON.parse(readFileData(config.summary_dir));
        fileNames.forEach(file=>{
            let sort = 0;
            sortData.forEach(sd=>{
                sort++;
                if (sd.file.indexOf(file.name) > -1){
                    _writHeadInfo(path.join(file.path, file.name), { Title: sd.alias, sort: sort});
                    return;
                }
            });
        });
        let dirSort = 0;
        sortData.forEach(sd=>{
            dirSort++;
            let thepath = path.join(config.content_dir, sd.file);
            let stat = fs.lstatSync(thepath);
            if(stat.isDirectory()){
                fs.writeFileSync( path.join(thepath, 'sort'), dirSort, 'utf8');
            }
        });
      callback(1);
    }
    return (req, res)=>{
        // if(req.param('token') !== config.authority_token){
        //     res.json({ status: 400, message: "no server" });
        //     return;
        // }
        console.log("[INFO]  summary:"+config.summary_dir);
        fs.exists(config.summary_dir, (exist)=>{
            if (!exist){
                res.json({ status: 500, message: "file not exist" });
                return;
            }
            WritfileSort(config.content_dir, (e)=>{
                res.json({ status: 200, message: "success" });
                return;
            });
        });
    };
}
module.exports = DocTools;
